package com.arron.algorithm.leetcodetop100.二叉树;

import com.arron.algorithm.tree.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 297. 二叉树的序列化与反序列化
 */
public class TreeNodeSerialize {




    public String serialize(TreeNode root) {

        if (root == null) return "#";

        String stringBuilder = root.val +
                "_" +
                serialize(root.left) +
                "_" +
                serialize(root.right);
        return stringBuilder;
    }

    public TreeNode deserialize(String data) {

        if (data.startsWith("#")){
            return null;
        }

        String[] s = data.split("_");



        return deserialize(new ArrayList<>(Arrays.asList(s)));
    }

    public TreeNode deserialize(List<String> strings){

        if (strings.get(0) .equals("#")){
            strings.remove(0);
            return null;
        }

        TreeNode treeNode = new TreeNode(Integer.parseInt(strings.get(0)));
        strings.remove(0);
        treeNode.left = deserialize(strings);
        treeNode.right = deserialize(strings);
        return treeNode;
    }

    public static void main(String[] args) {
        TreeNodeSerialize treeNodeSerialize = new TreeNodeSerialize();

        BuildTree buildTree = new BuildTree();
        TreeNode treeNode = buildTree.buildTree();

        String serialize = treeNodeSerialize.serialize(treeNode);

        System.out.println(serialize);

        TreeNode deserialize = treeNodeSerialize.deserialize(serialize);

        System.out.println(deserialize);
    }

}
